package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;

        String url=req.getRequestURI().toString();
        log.info("url:{}",url);

        if(url.contains("login")){
            log.info("登录操作，放行");
            chain.doFilter(request, response);
            return;
        }

        String jwt=req.getHeader("token");
        if(jwt==null){
            log.info("请求头token为空，返回未登录的信息");
            Result error=Result.error("NOT_LOGIN");

            String notLogin=JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息");
            Result error=Result.error("NOT_LOGIN");

            String notLogin=JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }
        log.info("令牌合法，放行");
        chain.doFilter(request, response);
    }
}
